┌──────────────────────────────────────────────────────────────────────────────┐│ Welcome to an Adventure in C ││ ││ Written by: Joaquin Valentine 1988 ││ Written in C using Borland's Turbo C (c) v1.5 │├──────────────────────────────────────────────────────────────────────────────┤│ All the commands needed are displayed on the last four lines. With Adventure││in C you can jump to a specific page, exit the program temporarily in order ││to run the examples, problems or any other program, or exit updating the data ││file which will keep track of the last page you were working on. You can also ││use the book mark feature to readily go back to a specific page if desired. ││ ││ This program was written using Borland's Turbo C (c). If any of the functions││mentioned here are not part of your compiler's library, check to see if there ││are similar functions provided or write your own. I have attempted to use ││standard functions which your compiler should accommodate. ││ ││ Thank you for using Adventure in C, I hope you will enjoy using this program ││in your quest for knowledge of the C language. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Learning a language, be it a foreign spoken language or a foreign computer ││ programming language, can either be fun or tedious. The following tutorial ││ was written with the idea that anyone crazy enough to enjoy programming must ││ be having a lot of fun at it! ││ ││ This "ADVENTURE IN C" is designed to be a computer aided instructional ││ program in which I have attempted to present the materials you need to begin ││ programming in C , along with some projects for you to complete. As with ││ any other language, you must "speak" in it in order to learn it. ││ ││ This tutorial is not designed to replace the many excellent volumes found ││ in your local bookstore but, hopefully, to get you started painlessly in ││ programming using C. You will need a C compiler and a text editor, or word ││ processor, which can generate ASCII files. In a pinch DOS's EDLIN editor ││ will do. ││ ││ ││ Now lets continue on.... │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ " What is C ? " ││ ││ C is a relatively "low level language" first developed for the UNIX ││ operating system and was an offspring of the B programming language. C, in ││ itself, is not a particular computer's program for it has no input/output ││ facilities other than those written by your compiler's publisher. This ││ attribute make C a "portable" language which, when written for portability, ││ can be compiled and run on another, different, computer. ││ ││ Already we may have come across some terms which you may be unfamiliar with││ so, before I continue, lets take a look at the terms: ││ ││ ││ SOURCE OBJECT EXECUTABLE ││ ││ INTERPRETER COMPILER ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Since a computer only understands a sequence of ones and zeros,(binary), ││ languages have been developed to make it easier for us humans to communicate ││ with the machines. BASIC, COBOL, FORTRAN and C are some of the many languages││ developed for this man to machine interface. The SOURCE code is the human ││ language code which we can understand and apply to programming. If you have ││ dabbled in BASIC you are familiar with the simple statement: ││ ││ 10 PRINT "HELLO WORLD" ││ ││ That little line is an intelligible statement in BASIC and will, when run, ││ print on your screen : HELLO WORLD ││ ││ By the way "HELLO WORLD" is a traditional greeting for programmers writing ││ their first program in a particular language. It will be also your first ││ project in this Adventure in C. ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Now that we know what the source code is, how does the computer translate ││ this human code into machine code ? ││ ││ There are two methods of accomplishing this and they are through the use ││ of a compiler or an interpreter. ││ ││ An interpreter is just that, it executes a program by translating the ││ source code as it is executing, just as an UN translator would. This is nice ││ way of doing things because all you need is the interpreter program and your ││ source code. The main disadvantage of this method of getting your program to ││ run is that it needs that highly paid (in memory) and slow (it has to ││ interpret as it goes along) interpreter. If you give your masterpiece ││ program to a friend, unless he has that interpreter also, all he can do is ││ read that nice, carefully written source code you gave him. Lets take a look ││ at a better solution...... ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ A compiler creates an executable file. An executable file is a file which ││ contains all the necessary runtime routines to execute the program. Actually ││ now we will have to create three files, the SOURCE, an OBJECT code file and ││ then the executable. How is this done? By performing a compilation (with ││ you trusty compiler) and then LINKING the compiled object files into an ││ executable file. Lets take a look at the steps..... ││ ││ ┌───────────┐ ┌────────────┐ ┌──────────────┐ ││ │Your source├────────>│ to the ├────────────────>│binary object │ ││ │ code │ is fed │ COMPILER │ which creates a │code file │ ││ └───────────┘ └────────────┘ └────┬─────────┘ ││ │ we now use the ││ │ LINKER which ││ ┌───────────┐ ┌────────────────────┐ ││ │executable ├<─────────────────┤links the object code│ ││ │ file │ and creates an │ with the libraries │ ││ └───────────┘ └─────────────────────┘ ││ Lets look at this some more............. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Once a function is written we can reuse the function in other applications.││ By maintaining files, called libraries, we can access those function without ││ having to rewrite them. The linker is the program which accomplishes this ││ by "linking up" separate object files. Not only can this be done for library ││ ( denoted as xxx.lib) files but you can create separate object files which ││ performs a process, which when linked all together creates a functional ││ program. ┌──────────────┐ ││ ┌────────────┐ which ┌──────────────┐ ┌───────┤binary object │ ││ │ to the ├──────────┤binary object │ │your │code file │ ││ │ COMPILER │creates a │code file │ │library└────┬──┬──────┘ ││ └─────┬──────┘ └────┬─────────┘ └────┬───────┘ │ ││ │ └──────────────┬────┴──────────┘ ││ is fed └───┐ we use the LINKER which ││ │ ┌───────────┐ and ┌──────────────────────────┐ ││ ┌─────┴─────┐ │executable ├<───────┤links the object code files│ ││ │Your source│ │ file │ creates│ with the library files │ ││ │ code │ └───────────┘ an └───────────────────────────┘ ││ └───────────┘ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Now its time to write your first C program. Remember I said that it was ││ traditional to print out "HELLO WORLD" as your first project? ││ ││ You will need to create a source code file on an editor, name your file ││ MYFIRST.C ( the extension .C is traditional for a C source code file). ││ Compile your program. ( Check your compiler's manual on how to perform ││ a compilation. ) For your source code enter the following : ││ ││ main() ││ { ││ printf("HELLO WORLD !!!!!"); ││ } ││ ││ ││ Make sure you type it as it is shown, if you want, jot it down on a piece of ││ scratch paper. After you have compiled and linked it to create an executable ││ (.exe) file type MYFIRST at the DOS prompt and view the result. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ If you completed that task CONGRATULATIONS !! You have taken your first ││ step into programming in C. The output from that small piece of code was: ││ ││ HELLO WORLD !!!!! ││ ││ The biggest accomplishment by you was NOT in copying the source code but in││ learning how to take that bit of source code, compiling and linking it to ││ an executable program. Lets take a look at the results. You should have ││ created the following files on your program disk. MYFIRST.OBJ and ││ MYFIRST.EXE. If you didn't run it, go ahead and enter <F1> to get into DOS ││ nd at the prompt type in MYFIRST. ││ ││ If you did, then just go on to the next page where we will take a closer ││ look at our first program. ││ ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Taking a closer look at the source we wrote, you can see its was made up of││ 4 elements:┌──────┐ ┌──┐ ┌────────────────────────────┐ ┌──┐ ││ │main()│ │{ │ │printf("HELLO WORLD !!!!!");│ │ }│ ││ └──────┘ └──┘ └────────────────────────────┘ └──┘ ││ C is a structured language, meaning that C follows an organized approach ││ to its syntax and logic. ││ ││ The basic unit of the C language is a "little black box" called a FUNCTION.││ A function is a routine which has been written by you, or others, which ││ performs a specified task. This is great for we can write a library full ││ of functions to perform certain tasks, and once written we can ignore ││ how they work for we only are concerned with what they do. A function can ││ easily be recognized by its signature: an open parenthesis and a closing ││ parenthesis:(). ┌─────────────────────────────┐ ││ ┌──────────>│main() │ ││ │ │{ │ ┌──────────────────┐ │├──────────┴──────────┐│ printf("HELLO WORLD !!!!!");│<─┤printf() is also a│ ││main() is a function.││} │ │ function │ │└─────────────────────┴┴─────────────────────────────┴──┴──────────────────┴───┘┌──────────────────────────────────────────────────────────────────────────────┐│ Before we continue, we need to look at the IDENTIFIERS , VARIABLES, ││ CONSTANTS and RESERVED WORDS in the C language. ││ ││ An identifier is a name for a function or variable in C. It can be a unique││ sequence of letters and digits , as long as it begins with a letter. The ││ underscore ( _ ) can also be used, as it is counted as a letter in C. In C ││ the letters are case dependent, which means that upper-case letters are very ││ different from lower-case letters. Some examples of identifiers are : ││ ││ COST cost AMOUNT amount The_Total the_total ││ ││ In each case the identifier is unique, for the compiler will treat COST as a ││ different name than cost. Certain words have a special meaning in C and ││ cannot be used as an identifier. These words are known as the RESERVED WORDS ││ and are completely listed in your C compiler manual. You will soon get to ││ become familiar with them as many perform certain tasks for program control, ││ such as the words: if, for, do, switch and sizeof. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ VARIABLES ││ ││ Variables are items which can change in value. Constants are of a fixed ││ value which do not change during the execution of a program. In C variables ││ and Constants must be declared before they are used. The process of declaring││ these items provides a place in memory where the items will be stored. ││ The declaration of a variable follows the following format: ││ ││ int total; /* declare total to be of the data type integer */ ││ char one_char; /* declare one_char to be of the data type character */ ││ ││ Things to note about a variable is that memory is allocated for the storage ││ of the variable and that the size taken up in memory depends on the data ││ type of the variable. Variables must first be declared before they are used ││ in your program and these declarations must be in the beginning of the block.││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ CONSTANTS ││ ││ Constants are not changeable. A 23 is a 23 and cannot become a 33. In C ││ examples for constants are: ││ ││ 58 a decimal -33 a negative decimal ││ 07 an octal (base 8) number ││ 0x6F a hexadecimal (base 16) number ││ ││ 233.7 a floating point constant ││10e-7 also a floating point number with a negative seven exponent ││ ││'A' a character constant ( notice the single quote marks enclosing A) ││ ││"This is a string constant" (notice the double quotation marks enclosing ││ the string) ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ THE ESCAPE SEQUENCE ││ ││ In C there are special characters which can be expressed through an ││ escape sequence. This sequence is preceded by the backslash (\) and a ││ special character or numerical value. The character is actually the same ││ as the number but easier to recall. Lets look at the character escape ││ sequences provided by C. ││ ││ SEQUENCE REPRESENTATION │├──────────────────────────────────────────────────────────────────────────────││ \n or \N newline ( it is the sequence for a carriage return and ││ linefeed) ││ \t or \T tab ││ \b or \B backspace ││ \r or \R carriage return ││ \f or \F form feed ││ \\ permits use of the backslash as itself ││ (more) │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ SEQUENCE REPRESENTATION │├──────────────────────────────────────────────────────────────────────────────┤│ \' permits the use of the single quotation mark as itself ││ \" permits the use of the double quotation marks as itself ││ \0 ASCII 0, the NULL, used to terminate a string amongst ││ other things. ││ \xxx Octal (base 8) numbers which represent a character ││ constant. An example would be the ASCII BELL character ││ 7 which beeps the speaker on your PC. You could represent││ the bell as \007. ││ ││ ││ ││ We will see later on that there is another way of declaring a constant ││ through the use of the preprocessor #define. But for now lets first look ││ at Data types and operators. ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ DATA TYPES ││ ││ The whole idea of creating a program is to manipulate some kind of ││ information. In C this data can take the form of an integer,a floating-point ││ number, texts in the form of a string or a single character, or pointers. ││ ││ Integers are whole numbers such as 1, 21, 666, -222, 0. ││ 3 ││ Floating point numbers are real numbers such as 1.5, 10 x 2 , -22.789. ││ ││ A single character, such as 'A',is enclosed by tick (') marks. ││ ││ A string is a sequence of characters enclosed by quotation marks ( " ), such ││ as "HELLO WORLD !!!!!". ││ ││ A pointer is a variable that contains the ADDRESS of a value in memory. We ││ will go deeper into pointers later in our Adventure in C. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Of the data types we discussed there are sub-type. Integers can be either ││ signed or unsigned. A signed integer has both a positive and a negative ││ attribute to them, whereas an unsigned can only be a positive number. To add ││ to this the integers can be either short, (normal) int or long. This concept ││ is dependent on the system you on running on and affects how much space in ││ bytes the variable uses. As an example on the IBM PC a short can be, again ││ dependent on the implementation of the compiler, only one byte long, a ││ integer (int) two bytes and a long (depending on your compiler) 4 bytes long.││ All that C guarantees is that a short will not be larger than an int or a ││ long smaller than an int. ││ ││ Floating point numbers can also be of two classes: a float or a double. ││ Again the difference is in the space allocated in memory for holding the ││ variable. A double permits more digits to be stored in the mantissa than a ││ float and thus provides "double precision" to calculations, increasing ││ accuracy. ││ ││ Keep these data types in mind when you are creating your programs. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Before we continue let's clarify what a statement and a block are in C. ││ ││ A statement is an expression which is always terminated by a semi-colon. ││ Some examples of C statements are: ││ printf("HELLO WORLD"); ││ value = 100; ││ ││ Braces { and } are used to enclose groups of statements or declarations and ││ creates a compound statement. An example would be for a conditional if: ││ ││ if(a==100) ││ { ││ printf(" Congratulations on an excellent score\n); ││ a=0; /* reset a to zero */ ││ } ││ ││ Notice the individual statements have the ; but the if is terminated by the ││ compound statement closing with the closing brace } │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ main() is a special function, for it is the master controller of a C ││ program. All functions have the following syntax: ││ ││ function_name(argument list, which is optional) ││ ││ As we progress through this Adventure in C we will come back to the main ││ function to see what arguments can be used with it, how functions are ││ declared and function types. ││ ││ Let's take a look at a function we just used and see how functions operate:││ ││ The printf() is a standard function provide by C. This function provides ││ an output to the stdout (standard output), which is normally your screen. ││ Its ARGUMENT was the STRING "HELLO WORLD !!!!!". As you can see functions can││ call upon functions to produce a result, in this case the main() function ││ used the printf() function to output to the screen "HELLO WORLD !!!!!". ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Functions normally return a value of some kind, but it is up to the ││ calling routine to determine if it is going to use it or not. ││ ││ A function takes control of the program when it is called and retains ││ control until such time as it either ends or "returns" . ││ ││ main() control┌─────> function_a() ││ { passes │ { ││ int x; to │ statements; ││ ┌─> x=function_a();────────┘ statements; ││ │ printf("%d",x); ┌───── return (some result); ││ │ } │ } ││ └────────────────────────────┘ ││ the result is returned to ││ the variable x ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Functions, unless declared so, are assumed to return an integer of type ││ int. For most purposes this is sufficient, unless of course you want a ││ different data type returned. You must declare the function to be of the ││ desired data type if it is other than an int. ││ ││ An example of a function which returns nothing is : ││ ││ ││ void clrscrn() ││ } ││ /*statements to clear the screen */ ││ } ││ ││ This function would clear the screen, of course we haven't yet added the ││ statements, and return control to the calling program without returning ││ any value. There are many instances where you only wish to perform some ││ process without returning anything to the caller. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Functions normally have argument list with them. The traditional method ││ of declaring a function is in the creation of a function header. The draft ││ ANSI C modifies this header for ease in locating syntactical errors. The ││ following examples illustrate the creation of a function: ││ ││ TRADITIONAL C PROPOSED ANSI STANDARD ││ ││ int sum(x,y) int sum (int x, int y) ││ char *a_line; { ││ { return(x+y); ││ return (x+y); } ││ } ││ The above function whose name is sum returns an integer value of the sum of││ x and y. A function does not have to have arguments and does not have to ││ return any values, that is all up to you. A function which returns or accepts││ nothing could be: void function_name() │void function_name (void) ││ { │ { ││ /* body of the function */ │ /* body of the function │└─────────────────────────────────────────────────┴────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Functions can return prior to its end through the use of the keyword ││ return. ││ ││ ││ float what_ever(x,y) ││ float x,y; ││ { ││ if(this is true) ││ return(x/y); ││ more_statements; ││ } ││ ││ There is another drastic way of exiting a function and that is through the ││ exit(0); statement. When the program sees exit(0); The program will terminate││ closing all files on its way out. ││ ││ Remember most of all, functions are just "black boxes" which you can put ││ to use in a C program. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ A look at printf() ││ ││ As with, just about anything in C, output is performed by some function. ││ You already tried one of the most useful of these functions printf(). ││ ││ printf() is a formated print function which outputs to the standard output. ││ ││ The Format for printf() is : printf( <"a format string">,arg1,arg2,arg..>); ││ where printf is the functions name (notice the open bracket "("). The format ││ string, which is a string of characters dictating the format of the output. ││ and a list of arguments separated by commas, which tell the function what ││ you want formated by the format string. Take a look at the following example ││ for a clearer idea: ││ ││ printf("The total is: %d",total); ││ ││ You can probably guess what words will be printed, but what about the funny ││ looking " %d" in the statement. And what does the total have to do with it ? │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The % (percent sign) in the format string is a special character which ││ tells the function printf() "OK now comes the type of data I want you to ││ print out, and that data is located in total." The %d is known as a format ││ specifier for an integer (d=digit). Remember all those data types, well here ││ is one place you need to know what you are manipulating. ││ Let's look at some other specifiers and what data types they detail. . ││ ││ DATA TYPE │ SPECIFICATION │ REMARKS │├────────────────┼───────────────────┼─────────────────────────────────────────┤│ INTEGER │ %d │ (digit) 1 2 66 -222 ││ LONG │ %ld │ (long digit) 434,444 ││ FLOAT │ %f │ (float) 2.143 3.14 ││ CHARACTER │ %c │ (character) a H ││ STRING │ %s │ (string) "HELLO WORLD" │├────────────────┴───────────────────┴─────────────────────────────────────────┤│ We will now take a big step and see how we can use printf() and some other ││ statements to rewrite our "HELLO WORLD" message. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ To output the data truly formated C has a width and precision specifier. ││ ││ The width specifier states " This is the minimum number of "spaces" ││ reserved for this value". This specifier is a number following the % sign. ││ The width specifier n (a number) states that at least this many characters ││ will be outputed. If the number of characters is less than the specifier than││ the output is right-padded with blanks. If the specifier is a negative number││ it is left-padded. If a zero (0) precedes the number than if the value is ││ than the width specified it will be padded-left with zeros. ││ An example for the string "HELLO FELLOW PROGRAMMER" (22 characters) ││ 1 2 3 4 ││ specifier 01234567890123456789012345678901234567890 ││ %10s HELLO FELLOW PROGRAMMER ││ %30s HELLO FELLOW PROGRAMMER ││ %-30s HELLO FELLOW PROGRAMMER(blanks)_ ││ ││ PROJECT: Use the width specifier to output an integer starting in column ││ 20 of your screen, left-padded with zeros for any number using %5d. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The precision specifier can be used for floating point numbers or strings. ││ This additional specifier is a positive number which follows a period. ││ When used with floating point numbers the precision gives the number of ││ digits to output at the right of the decimal point. If used with a string, ││ it states what is the maximum number of characters to output from the string.││ Using both a width and precision specifier for a string we have for our ││ example: "HELLO FELLOW PROGRAMMER" (22 characters) ││ ││ 1 2 3 4 ││ specifier 01234567890123456789012345678901234567890 ││ %30.10s (blanks)HELLO FELL(b l a n k s) ││ ││ for a float whose value is 38.729 ││ 1 2 3 4 ││ 01234567890123456789012345678901234567890 ││ ││%f5.2 38.73 ( note the rounding off of the ││ number) │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ One more thing with printf, the data being outputted can also be computed ││ within the argument list, as well as span lines with the use of the ││ backslash \ operator. Lets try it out. ││ main() ││ { ││ printf(" Now is the time \ ││for all good men \ ││to come to the aid\n\ ││of thier country"); ││ ││ The backslash here permits us to go to another line without it you would ││ probably get an error when you tried to compile it. ││ ││ See if you can imagine what the actual output is from this? ││ ││ ││ There is more to come ││ as you continue on your adventure in C │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Look at the following source code: ││ ││ main() ││ { ││ char message[12] ="HELLO WORLD"; ││ printf("%s",message); ││ } ││ ││ The above example created an array of characters (called a string) into a ││ variable called message. The specifier in printf() is for a string whose ││ contents are located in the variable message. But why a length of 12 for ││ 11 characters ? ││ In C there are special control characters which perform special tasks. A ││ string is always terminated by the special charcter '\0', called NULL. this ││ tells the function "Thats the end of this string." Since we initialized the ││ variable message with our string the compiler handles the insertion of the ││ NULL character for us. Try it and see. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Now write a program which assigns a constant to an integer, a float, ││ a character and a string. Use the width and precision specifiers to aline ││ the output into a table. ││ ││ Don't be limited by the directions look into your manual and see what ││ other format specifiers you can use and add them to your program. ││ ││ Try out some of the other I/O functions supplied such as ││ ││ putc() for outputting a single character. ││ puts() for outputting a string ││ ││ If something is not working study the examples in your manual and ││ see what was wrong. Unfortunately I cannot grade your work, besides only ││ your own satisfaction counts anyway. ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Still not very useful is it ? We need to start manipulating data not just ││ outputting something we already know. ││ ││ Arithmetic operators are tools to perform mathematical operations and are: ││ ││ ┌────────────┬──────────────┬────────────────────────────────────────────┐ ││ │ operators │ operation │ examples │ ││ ├────────────┼──────────────┼────────────────────────────────────────────┤ ││ │ = │ assignment │ total = 1200; c = 'a'; amount = 12.56; │ ││ │ * │multiplication│ total = 600 * 3; amount = 12.56 * 1.5 │ ││ │ / │ division │ half = 222 / 2; │ ││ │ + │ addition │ sum = 17 + 16; sum = 12.89 + 2.7; │ ││ │ - │ subtraction │ difference = 124 - 67; │ ││ │ % │ modulo │ (only for integers ) 10 % 2; yields 0 │ ││ └────────────┴──────────────┴────────────────────────────────────────────┘ ││ ││ The modulo (%) operator yields the remainder of a division. 10 % 2 = 0, ││ 11 % 2 yields a 1. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ There are also relational operations which are used for comparisons and ││ testing two operands. These operators are: ││ ┌────────────┬──────────────┬────────────────────────────────────────────┐ ││ │ operator │ operation │ examples │ ││ ├────────────┼──────────────┼────────────────────────────────────────────┤ ││ │ < │ less than │ if( a < 10 ) │ ││ │ <= │less than or │ if( total <= 100) │ ││ │ │ equal to │ │ ││ │ > │ greater than │ if( a > 10 ) │ ││ │ >= │greater than │ if( total >= 100) │ ││ │ │or equal to │ │ ││ │ == │ equal to │ if(flag == TRUE) │ ││ │ != │not equal to │ if(flag != TRUE) │ ││ │ │ │ │ ││ └────────────┴──────────────┴────────────────────────────────────────────┘ ││ ││ NOTE the difference between the assignment operator ( = ) and the ││ relational operator ( == ). Confusing the two can cause some real headaches. │└──────────────────────────────────────────────────────────────────────────────┘┌ ─────────────────────────────────────────────────────────────────────────────┐│ To add to the relational operators there are also Logical operators which ││ produce a value of 0 (FALSE) or 1 (TRUE) these are : ││ ┌────────────┬──────────────┬────────────────────────────────────────────┐ ││ │ operator │ operation │ REMARKS │ ││ ├────────────┼──────────────┼────────────────────────────────────────────┤ ││ │ && │ logical AND │ True only if both operands are true. │ ││ │ || │ logical OR │ True if one of the operands is true. │ ││ │ ! │ Logical NOT │ zero if the operand is non-zero, non-zero │ ││ │ │ │ if the operator is zero. │ ││ │ │ │ │ ││ ┌┴────────────┴──────────────┴────────────────────────┬───────────────────┤ ││ │ AND OR NOT │ F = FALSE = 0 │ ││ └─────────────────────────────────────────────────────┤ T = TRUE = 1 │ ││ F && F = F F && F = F !T = F └───────────────────┘ ││ F && T = F F && T = T !F = T ││ T && F = F T && F = T ││ T && T = T T && T = T ││ T = TRUE F = FALSE │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The arithmetic operators also have a sort of shorthand which is shown ││ below : ││ ││ a += 3; is the sane as a = a + 3; ││ ││ a -= 4; is the same as a = a - 4; ││ ││ a *= 6; is the same as a = a * 6; ││ ││ a /* 8; is the same as a = a / 8; ││ ││ a %=2; is the same as a= a % 2; ││ ││ Kind of nice isn't it ! But wait it gets even easier for some other ││ everyday math such as just incrementing a variable only by 1 or decrementing ││ a variable only by one. Go on to the next page for these operators.... ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The INCREMENT and DECREMENT operators are simply ++ and -- respectively ...││ ││ k++; is the same as k+=1; or k=k+1; ││ k--; is the same as k-=1; or k=k-1; ││ ││ There's more though for the operators -- or ++ can go before or after the ││ variable, and depending where they are changes what result you may get. ││ ││ If the operator is before the variable it is a preprocessor, if it is after ││ it is a post-processor. Examples are , if k is equal to 10,: ││ ││ d = ++k; Here d is equal to 11 for the k was incremented first. ││ d= k++; Here d is equal to 10 but k WILL BE equal to 11 after the ││ statement is executed. ││ ││ This increment or decrement is not really by one either, but by one unit ! ││If the data type is a pointer, for example, the size of the pointer increments││the pointer. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Finally, there are operators which work on individual bits of a number. ││ These are the bitwise operators. Of these only the negate ( ~ ) operator ││ requires one operand. The bitwise operators are: ││ ( NOTE the results are dependent on the type on digit (signed or unsigned)) │├──────────────────────────────────────────────────────────────────────────────┤│ ~ negate Takes the compliment of the bits, an example is:││ if the number is unsigned 4 then in binary it is ││ represented as 00000100. ││ the bitwise negate of 4 : ~4 is then ││ ~00000100 results in 11111011 or 253 ││ ││ >> shift right Shifts the bits right by the specified operand. ││ An example is unsigned 22>>2 which means shift ││ the bits in the number 22 right twice. ││ 00010110 >> 2 yields 00000101 ( 3 ). ││ ││ The example uses unsigned digits for explanation. If the numbers were signed ││( the highest bit designating positive or negative), the results would differ.│└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ << shift left Shifts the bits left by the specified operand. ││ An example is 4 << 2 which means shift the bits││ in the number 4 left twice. Again, using an ││ unsigned integer: ││ 00000100 << 2 yields 000010000 ( or a 16 ) ││ ││ Notice that a shift of one is the same as doing a││ multiplication by 2. In the previous shift right ││ a division by two for each shift is accomplished.││ ││ & bitwise AND Not to be confused with the address of operator ││ which is also an &, the bitwise AND performs a ││ bit by bit logical AND on two operands, as in: ││ 20 & 4 yields 00010100 (20) ││ AND 00000100 (4) ││ ─────────── ││ 00000100 (4) ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ ^ exclusive OR This operator performs a bitwise exclusive OR ││ (XOR) , meaning if the bits are of the same ││ value a zero results , otherwise a 1 results ││ Look at this example : ││ 6 ^ 2 00000110 (6) ││ XOR 00000010 (2) ││ ────────────────── ││ 00000101 (5) ││ ││ ││ | Bitwise OR Performs an inclusive OR on two operands. meaning││ if one bit is a 1 then the resultant bit will be ││ a one. An example of this is : ││ 20 | 4 yields 00010100 (20) ││ OR 00000100 (4) ││ ─────────── ││ 00010100 (20) ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ If you unfamiliar with bit operations, read your compiler's manual on ││ these operators or do some research at the library. There are many fine ││ introductory books on computers which will help clarify these operators. ││ ││ There are only two operators left which nay seem confusing at first but ││ are used very extensively in C, there are the ADDRESS OF operator and the ││ CONTENTS OF operator. ││ ││ The ADDRESS OF operator is the & sign ( similar to the bitwise AND ) ││ Don't get these confused ! The bitwise AND operator is used between two ││ operands. The ADDRESS OF operator requires ONE operand and that operand must││ be a variable. This operator gives the ADDRESS of the variable in memory. ││ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ││ The CONTENTS OF OPERATOR is the * sign. Again don't confuse it with the ││ arithmetic multiplication sign (*). This operator requires one operand and ││ results in the CONTENTS OF the value residing in the ADDRESS OF the variable.││ ││ Here we hit the meat of C, and its name is POINTERS....... │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ A pointer is just that, a data type which points to a location in ││ memory. Imagine our first project,"HELLO WORLD !!". The string "HELLO ││ WORLD", when loaded in to variable message became stored somewhere in the ││ computers memory. Lets say that location was cells 62 through 75 in the ││ computers memory banks. With POINTERS we can look at cell 62 and see that ││ it has an "H" in it, likewise cell 75 has the escape sequence '\0', which ││ is the NULL ( or "That's the end of this string" marker). ││ If the variable was called : a_line, and this variables address could ││ be found, we could pick out whichever letter was contained within a_line. ││ ││ 62 63 64 65 66 67 68 69 70 71 72 73 74 75 ││ ┌───┬───┬───┬───┬───┬──┬────┬───┬───┬───┬───┬───┬───┬───┐ ││ │ H │ E │ L │ L │ O │ │ W │ O │ R │ L │ D │ ! │! │\n │ ││ └───┴───┴───┴───┴───┴──┴────┴───┴───┴───┴───┴───┴───┴───┘ ││ ││ You should be able to see how powerful C can get when you can access the ││ data not only by its variable, but by its address in memory. This capability ││ will come to light as we continue in our Adventure in C. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ We still need some more tools to work with in C , one of the most ││ helpful to a programmer is the neglected COMMENT. A comment is just the ││ programmers explanation of what is going on in the program. They are ││ ignored by the compiler, but sure make it easier to modify or locate an ││ error than just pages full of code. The comment is enclosed by the opening ││ of the comment : /* and the closing of the comment : */ ││ Comments should be included anywhere you are performing a process so as to ││ describe the operation. ││ ││ /* This is the MYFIRST.C source code */ ││ main() /* the main controlling function*/ ││ { /* open up the block for main */ ││ printf("HELLO WORLD !!!!!"); /* used the printf function to display ││ HELLO WORLD !!!!!, notice this comment ││ spans lines till its see the end of the││ comment -> */ ││ } /* that's the end of the block called main. */││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ STORAGE CLASSES ││ ││ In C all variables have some storage class. This means that all variables ││ are stored in a specific manner. There are three classes of storage: auto, ││ extern and static. ││ ││ The auto(matic) class is the most frequently used storage class. They are ││local variables and are declared inside of the function. This class of ││variable minimizes the amount of memory needed by the program, for the memory ┤│required is allocated only when the function is called. ││ ││ An example of this class is: ││ ││ main() ┌──────────────┐ main() ││ { │or just plain │ { ││ auto int price; └──────────────┘ int price; ││ } } ││ By default variables are in the auto class, unless you declare them as..... │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ either extern or static. ││ ││ The extern(al) class of variable is used to permit a variable to be defined ││outside a function. This outside variable, a global variable, retains its ││value though all functions using it, and can be modified by those functions. ││This global is readily accessible to functions within the same source code, ││but for separate compilations ( two separate sources compiled to object files)││one object has no idea of the variable from the other. Through the use of ││extern no space is allocated for the variable, for this class declares that ││it has been defined elsewhere. An example of this class is : ││ ││ SOURCE 1 ║ SOURCE 2 ││ int total; ║ function_b () ││ function_a() ║ { ││ { ║ extern int total; ││ /* function an access total */ ║ /* this function too can access ││ } ║ total */ ││ ║ } │└─────────────────────────────────────╨────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ An extern variables can access variables outside of themselves, static ││ variables allocate storage for themselves but prohibit access from the ││ outside. This is useful in protecting data from being modified by some ││ external function and provides a level of information hiding to the outside. ││ ││ If the static variable is external to a different source, static only to ││ its own source file, it is accessible to any function within that particular ││ source file but not accessible to any other source files. ││ If the static variable is internal, that is a static variable declared ││ within a function, only that function has access to that variable. ││ ││ The contents of a static variable exist even if the function is not being ││ called. This is unlike auto variables which are created only when the ││ function is in use then deallocated when the function has ended. ││ ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Another tool kit provided by C are the PREPROCESSOR statements. ││ These statements all begin with the # sign and extremely useful for program ││ development. The first one we will look at is the #include. ││ ││ The #include statement is used to include another C source file during a ││ compilation. If you look at your compilers directory information, you will ││ notice some *.h files. These are header (.h) files used to define or ││ to describe macros, type definitions and other required definitions for ││ functions or constants used by your program. A good example is the header ││ file STDIO.H , which is the standard input-output header file. If you look ││ at this file you will find definitions for the standard input (stdin), ││ standard output (stdout) and standard error (stderr), as well as other ││ standard I/O definitions. If you wanted to use the stdin, for example, ││ within a function, you would need to know what stdin was, in relation to ││ system. The easiest way is to include it into your source code using the ││ #include statement. ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ C also provides for macro substitution with the use of the #define ││ preprocessor. A simple example of the preprocessor #define is : ││ ││ #define FALSE 0 ││ #define TRUE !FALSE ││ #define err_msg " OOPS! You made a mistake" ││ ││ In the above examples we have defined the identifier FALSE as being the ││ constant zero, True is a value that is NOT FALSE and err_msg is the string ││ which could be used in a printf() to output an error message. Whenever the ││ compiler comes across the word FALSE it will substitute a zero in its place, ││ or if the indentifier is err_msg the string will be substituted, as in ││ ││ #define err_msg " OOPS! You made a mistake" ││ main() ││ { ││ printf(err_msg); /* this becomes printf(" OOPS! You made a mistake"); */ ││ } │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Before we write another program we need to look at printf()'s sister ││ function which inputs data into the program. This is the scanf() function. ││ scanf() has the syntax very similar to printf, with one very, very ││ important difference which we will see. ││ ││ scanf(<argument list>,&arg,&arg2,&arg3,&arg..); ││ ││ Notice the ADDRESS OF operators for the arguments. C passes arguments to ││ functions by value. Passing by value means that when data is passed to a ││ function the receiving function only makes a copy of it, the function cannot ││ alter what was passed, but can work on its copy all it wants to. In order for││ a function to alter the data passed to it it must be passed by reference. ││ Here is where pointers come in. To pass by reference the calling function ││ must pass the address of the variable to the called function. Once the ││ called function knows where the variable "lives" in memory it can replace ││ that value. By giving scanf(), for example, the address of arg1, scanf() can ││ go to arg1's location in memory and place in it the data you wished inputted.││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Lets try a program to see how all this works. ││ /* PROGRAM 2 */ ││ ││ #define prompt " Enter a single character \n" /* notice the newline */ ││ main() ││ { ││ char ch /* ch is declared as an auto class character */ ││ printf(prompt); ││ scanf("%c",&ch) /*get the data from the stdin and place the char into ││ memory location located at the address of ch */ ││ printf("\n The character you entered is a %c",character); ││ } /* ││ ││ Note that a newline was performed before the remainder of the last string*/││ ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ There is another special character for the scanf(). This is the * again, ││ but in the scanf() argument list this say "Skip this field ". ││ Can you think of what happened to the carriage return linefeed you placed ││ into keyboard buffer when you entered a number. Unfortunately its still ││ there. Add the following line to program 2 and see what happens. ││ ││ scanf("%c",&ch); ││ printf(" NOW WE GOT %c",ch); ││ ││ You probably observed that "NOW WE GOT " and some kind of junk. That's ││ because by entering you placed another character into the buffer. We can ││ skip this entry by adding to our argument control list the following: %*c, ││ in all the scanf() calls ( scanf("%c %*c); ). Try it and see the results. ││ ││ There also happens to be another problem with scanf(), especially when you ││ are dealing with strings. Can you think of what that may be. Try modifying ││ program 2 for a string array ( char a_string[30];) and just try to get your ││ full name printed out using only one scanf() with one control argument. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ You should have come up with something similar to this: ││ #define prompt " Enter a your name \n" ││ main() ││ { ││ char a_string; ││ printf(prompt); ││ scanf("%s",&a_string); ││ printf("\n Is your name only: %s",a_string); ││ } ││ /* end of program */ ││ ││ You only got the first name didn't you? That's the problem with scanf(), ││ once it sees whitespace, a space, tab or a newline, it thinks its job is ││ done. ││ Pause for a few minutes and make sure that you understand and feel ││ comfortable with what you have learned. Next we will look at controlling ││ your programs flow and in doing so begin to write programs which will perform││ differing statements dependent on a test. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ IF and ELSE ││ One of the basic tests needed to come up with a decision is : if something ││ is true then we want to do this process, if its not then do something else. ││ ││ The syntax for the if-else statement is: ││ ││ if(this expression is true) ││ statement_1; ││ else ││ statement2; ││ ││ Note that the else is optional, you are not required to have it in an if ││ statement. Also note that the statement is not limited to one statement for ││ we can make a a Block statement: ││ if(expression) ││ { statement_1; ││ statement_2 ; ││ } │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ You can also do multiple conditional test by using the else if construct. ││ ││ if(expression) ││ statement; ││ else if(expression) ││ statement; ││ else ││ statement; ││ ││ C also has a short hand for simple conditional test. This is through the use││ of the ? operator. The ? operator performs like this: ││ ││ expression1 ? expression2 : expression3 ││ if expression1 is true then do expression 2. If expression1 is false do ││ expression3. An example of this operator could be: ││ ││ (a<70) ? printf("We have a failure in C"); : printf(" Passed the test"); ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ BUT FIRST...., thought you get away without trying some of these things out, ││ didn't you ? ││ ││ Write a program which performs like a calculator doing addition, ││ multiplication, subtraction and division. Make it as simple or as complex as ││ you want. Think of what you are trying to accomplish. Write out your thoughts││ into a flowchart or pseudo-code. I'll give you a simple suggestion : ││ ││ calculator program ││ 1. display a menu for either adding, subtracting, multiplying or dividing ││ to numbers. ││ 2. Using the if statement determine which arithmetic function you want to ││ do. ││ 3. Decide what prompts you want and then input the numbers needed. ││ 4. Output the results. ││ Remember what data types you need to do the calculations. Experiment and ││ explore that's the real Adventure in C. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ THE SWITCH ││ ││ The if-else is a good control statement with many uses, but what happens ││ you had to make 10 branches dependent on some result ? C provides for this ││ multiple-decision conditional test with the switch, this construct follows: ││ ││ switch(an integer expression) ││ { ││ case 1: statement_1; ││ break; ││ case 2 : statement_2; ││ case 3 : ││ case 4 : staement_3; ││ break; ││ default: default_statement; ││} ││ ││ Lets take a closer look at this control statement. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The "cases" which matches the expression following the switch statement ││ are executed. To skip over any other statements, and exit the switch, the ││ break keyword is used. Break exits the ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ││ block in is presently in. The keyword █ switch(an integer expression) █ ││ continue would cause the program flow █ { █ ││ to go back to the switch statement and █ case 1 : statement_1; █ ││ re-evaluates the integer expression █ break; █ ││ once again. The keyword case is followed█ case 2 : statement_2; █ ││ by a constant then a separator (:). █ case 3 : █ ││ If the expression resulted in a 1 █ case 'A': statement_3; █ ││ statement one would execute, then it █ break; █ ││ would "break" out of the switch. █ default: default_statement; █ ││ If the expression resulted in a 2, █ } █ ││ statements_2 and _3 would execute for ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ││ there are no breaks between case 2 and case 4. Cases 3 and 'A' would only ││ execute statement 3. If the evaluation did not match a case an optional ││ default "case" can be used to handle those instances. Remember to your ││ computer characters are numbers, represented in an ASCII code. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ ASCII, American Standard Codes for Information Exchange, are simply ││ integers which are interpreted as characters. Lets write a program now that ││ will output to the screen the standard ASCII character set, it's decimal, ││and hexadecimal value, and while were at it introduce the control loop: for ││ ││ The for statement performs a repetitive loop while a condition exists. This ││ statement take the form: ││ for( expression_1 ; expression_2 ; expression_3) ││ statement; ││ ││ expression one can be any expression and is only evaluated once. Normally ││ this expression is used to initialize some variable through an assignment. ││ Once expression_1 is evaluated expression_2 is evaluated. This is the ││ conditional expression and determines when the loop terminates. Expression_3││ can again be any expression but is normally used to increment the counter ││ for expression_2's evaluation. Any or all of these expressions can be left ││ out, as in : for (;;) , but then you will have a loop which would not end ││ unless you provide an "out" in the for's statements. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Project: Write a program that outputs the ASCII set with its output looking││ something like this : ││ Character Decimal value Character Decimal value ││ A 65 B 66 ││ ││ (try this for example in your code ) ││ ││ printf ("%5c %3d| ",ch,ch); ││ if (!(ch%4)) ││ putc('\n',stdout); ││ ││ ││ Can you see what the if statement is doing. Place it in your loop to ││ verify your thoughts. ││ ││ PS. You better skip ASCII 27, this is the end of file character and your ││ program will terminate abuptly. See which other characters you may ││ want to skip while your creating your program. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ There are two other control statements left for us to see, the do-while ││ and the while. The while statement states "While the expression is True ││ perform the following statements". ││ ┌──┐ ││ while(this expression is true) │or│ while(this expression is true) ││ statement; └──┘ { ││ statement_1; ││ statement_n; ││ } ││ In the while, the expression is first evaluated, and continues to execute ││ until the expression becomes FALSE (0). This may mean that the while may ││ never be executed because the expression may never be true. ││ ││ while(FALSE) ││ puts("This statement will never execute") ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The do-while loop checks the expression after the statements in the loop ││ are executed. This construct will always execute the statements at least ││ once. ││ do ┌──┐ ││ statement; │or│ do ││ while(expression is true); └──┘ { │├──────────────────────────────────┐ statement_1; ││ #include "stdio.h" │ statement_n; ││ main() │ } ││ { │ while(expression is true) ││ char c; └───────────────────────────────────────────┤│ do ││ { ││ puts("Enter a 'Y' to stop me"); ││ c=getc(stdin); /* getc gets a character from a file stream */ ││ } ││ while(c!='Y'); ││ } │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ fopen(filename,mode) is one function which opens a file. This function ││ returns a file pointer which you can use for inputting or outputting data. ││ The data type FILE is defined in the stdio.h and must be used, for remember ││ each implementation of C must accommodate differing systems. ││ ││ We need to look at how C handles input and output. ││ ││ In your stdio.h header file C has already defined three files for your use. ││ These three files are automatically opened when execute a program and ││ you already know that their names are stdin, stdout and stderr. ││ The stdin and stdout files can be redirected to other devices, such as a disk││ file or your printer using the redirection operator >. If you were at the ││ DOS prompt and did the following, the ASCII program were wrote earlier would ││ be printed out onto your printer: ││ A> PROG_2 >prn: ││ ││ Ok for some purposes, but we need more. Lets look at some of C's standard ││ functions for opening and closing a file. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ fopen(filename,mode) has three access mode: ││ "r" for reading from a file. ││ "w" for writing to a file. ││ "a" for appending to a file. ││ ││ If a file doesn't exit for reading an error occurs, and the function returns││ a NULL. If you were to write to a file that doesn't exit the function will ││ create one, and if you were to write to an existing file the contents of that││ file would be lost, replaced by the new file. ││ To add to the file the "a" append access mode is used. ││ ││ fclose(file_pointer) closes the file pointed to by the pointer returned ││ by fopen(). There are valid reasons for closing an opened file, first you may││ lose the data in the file if you do not close it and secondly you can only ││ open up a certain amount of files at at time. ││ ││ PROJECT: 1. create a text file with your editor. ││ 2. open the file and display its contents onto the screen. │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ An array is composed of a fixed number of data elements all of which are ││ of the same type. An example of a 7 element array of characters is: ││ ││ char a_line[7]; /* lets say a_line contains the word HELLO */ ││ ┌───┐ ││ Too access the elements of an array you must specify │ H │-> a_line[0] ││ a subscript after the array variable's name. ├───┤ ││ Notice that the first element "H" is the zero element│ E │-> a_line[1] ││ of the array and that the sixth element contains the ├───┤ ││ NULL character denoting the end of the string. │ L │-> a_line[2] ││ ├───┤ ││ When you reference an array without a subscript the │ L │-> a_line[3] ││ result is a pointer to the beginning of the array ├───┤ ││ This result is the same as taking the address of the │ L │-> a_line[4] ││ first element of the array or to express it in C: ├───┤ ││ │ O │-> a_line[5] ││ a_line == &a_line[0] ├───┤ ││ │\0 │-> a_line[6] │└──────────────────────────────────────────────────────┴───┴───────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Arrays can also be multidimensional. And are declared such as : ││ ││ char students [20][30] ││ int map [10][10] ││ ││ Multidimensional arrays are only limited by the amount of memory you have to ││create and store the elements. The variable students for example is an array ││of 10 elements whose individual elements is also an array of 10 elements. ││You can see that this variable takes 500 bytes of memory. How much memory ││would map need if it was declared as: int map[100][100][100]; ? ││ ││ A multidimensional array can be accessed in many different ways. Let's use ││draw students out using a 3x6 array and see what it looks like and how we can ││access the data within. ││ ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ char student [3][6]; ││ 0 1 2 3 4 5 ││ ┌──┬──┬──┬──┬──┬───┐ ││ 0│ J│A │C │K │\0│ │ ││ If we were to use only the ├──┼──┼──┼──┼──┼───┤ ││ array name then we would 1│ S│U │E │\0│ │ │ ││ have the pointer to the ├──┼──┼──┼──┼──┼───┤ ││ beginning of the array or 2│ B│ O│B │B │ Y│\ 0│ ││ &student[0][0]; └──┴──┴──┴──┴──┴───┘ ││ ││ To access SUE in the array you would want the string starting at [1][0] till ││ [1][3]. Again this can be done simply by stating student[1] which is the ││ array element which consists of the elements [1][0] through [1][5]. ││ ││ REMEMBER when you declare what the elements are you are declaring how many ││ elements are contained for the variable, but when you wish to access an ││ element you must start at element 0 NOT element 1. ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ A pointer points to a location in memory where an object resides. ││ In C pointers clarify what you are looking at, although they are probably ││ the least understood of all the C types. Just remember that a pointer points ││ to the actual location in memory where the data resides. When an array is ││ referenced without a subscript you obtain a pointer to the array. Lets write ││ a program which uses a pointer to access a multiple array of names. First ││ we want to have an idea of how we are going to write this program. One good ││ way is to write a pseudo-code of the program. A pseudo-code is just an ││ of how you wish to write your program. for this example lets write a pseudo- ││ code for pointers.c. ││ pseudo-code for pointers.c ││ declare an array of characters which contain the names of Jack,Sue and Bobby ││ declare an pointers which we will assign to the names array to see how ││ pointers operate, name_ptr. ││ assign the array names to the pointer name_ptr. ││ print out the names from the pointer. ││ end of pseudo- code. ││ Go on to the next page for this programs listing.│└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ /* pointer.c */ ││ ││ #include <stdio.h> /* header file for putc definition */ ││ main() ││ { int i; /* we will need this for the loop control */ ││ char names[3][6] = {"Jack","Sue","Bobby"}; /* initialize names */ ││ char *name_ptr; ││ ││ /* lets use our for statement to print out the three names after assigning ││ the pointer to its respective array */ ││ for(1=0;i<3;i++) ││ { ││ name_ptr = &names[i]; ││ puts(&names[i]; /* print out the array from the address of the names array*/││ puts(name_ptr); /* print out the name which whose address was assigned to ││ name_ptr */ ││} /* notice no contents of operator in the next line as we assign the location││ of names to name_ptr */ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ C provides a way to group different variables together into a template ││ called a structure. By template I mean it shows how the collection is ││ organized and gives it a template name. To visualize this imagine a template ││ for students in a class. You would probably need their last name, first name,││ a class number and a grade. If we were to draw a template of this it could ││ look something like this: ││ ┌───────────────────────┐ ││ │Template name:students │ struct students ││ ├───────────────────────┤ { ││ │ Last name │ char last_name[30]; ││ ├───────────────────────┤ ││ │ First name │ char first_name[30]; ││ ├───────────────────────┤ ││ │ Class number │ int class_number; ││ ├───────────────────────│ ││ │ average_grade │ float average_grade; ││ └───────────────────────┘ } ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ The structure can have an optional named called a structure tag if ││ desired. This was the word students in the structure we first looked at. ││ It is best to give a structure a name for you can readily remember why you ││ made the structure in the first place. ││ Lets take a look again at the structure and identify its parts: ││ ┌───┐ ┌─────────┐ ││ keyword for a structure┘ └ the structure tag ││ struct students ││ { ││ Last name string ──────> char last_name [30]; ││ First name string──────> char first_name[30] ││ Student's grade ───────> int class_number; ││ Student average ───────. float average; ││ } my_students; <─────── a variable whose structure││ is that of students. ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ A structure can have another structure as a member, or itself as a member. ││ This concept will be saved for an advanced C tuorial. For the time being ││ we will stay with the looking at how to declare a structure and some uses ││ we will put them through. ││ ││ Structure members can be referenced by using the member operator, which is ││a period (.). If for example, you declared my_students as being of a structure││whose tag was students you can easily access any of my_students data like so: ││ ││my_student.last_name ││my_student.first_name ││ You can now perform some process with or to the member : ││ ││ my_students.grade = 95.6; ││ or ││ printf("%s %s grade for this semester is :%f",mystudent.first_name\ ││ mystudent.last_name,mystudent.avaerage); ││ Of course more than one structure would be used if you have more than one... │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ student. You can treat the variable, which is structure just like any other ││ and create arrays of structures so that ││ ││ struct students my_student[10]; ││ ││ now is an array of structures for up, to 10 students. ││ ││ You can now access your fourth student as ││ ││ mystudents[3].last_name ││ ││ to gain access or change what students last_name is for the fourth student. ││ ││ There is even an easier way of accomplishing this. Through the use of ││ pointers you can point to the data you wish to access. Let's go on and ││ see how this is done. ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Well do it with an example: ││ ││ struct phone_book ││ { char last_name [30] ; ││ char first_name[30] ; ││ char phone_number[12]; /* phone number format xxx-xxx-xxxx */ ││ }; ││ ││ ││ struct phone_book *my_phbook; ││ ││ my_phbook->last_name = "JONES"; ││ my_phbook->first_name ="JOHN"; ││ my_phbook->phone_number="808-222-1234"; ││ ││ The - with the greater than > sign make up the pointer operator ->, and ││ it does suggest you are pointing somewhere. There is one problem with ││ this, and that is how does you program know how big my_phbook is ? │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Actually the best reason to use pointers is that you can allocate and ││ deallocate memory on the fly. This is possible through the use of the ││ memory allocation functions malloc() or calloc(). ││ ││ malloc returns a pointer to a block of memory that has the number of ││ bytes you wanted. its format is ptr =malloc(number of bytes). ││ ││ calloc returns a pointer to a block of memory also but is easier to ││ determine how many bytes are required for its format is : ││ ptr=calloc(number_of_units , unit_size); ││ ││ when in doubt C provides a function which will calculate the size for you ││ and this is the sizeof function. So now, if we had no idea of the size of ││ my_students we can still allocate memory for it by stating: ││ ││ my_students=calloc(1,sizeof(students)); ││ ││ I'll start you off but you need to complete the next assignment on your own..│└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ /* struct.c */ ││ ││ struct phone_book ││ { char last_name [30] ; ││ char first_name[30] ; ││ char phone_number[12]; /* phone number format xxx-xxx-xxxx */ ││ }; ││ main() ││ { ││ struct phone_book *my_phbook; ││ /* you write the code to 1- enter in a list of names and phone numbers. ││ 2. save the listing on disk ││ 3. retrieve a phone number by entering a name ││ 4. If the name isn't in your phone book add it ││ to the end. ││ ││ Remember that if no memory is available the allocation functions will return ││ a null pointer, use this for an error indicator */ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ References used in creating this tutorial are listed below. I have ││ attempted not to use any of the examples or wording from the references and ││ apologize to the authors if I had inadvertently used a concept or phrase ││ which are within their copyright. ││ ││ "The C Programming Language", Kernighan and Ritchie (1978) ││ " Turbo C (c) User's Guide", Borland International (1987) ││ " Mix C Compiler", Mix Software ││ ││ ││ ││ ││ ││ ││ ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘┌──────────────────────────────────────────────────────────────────────────────┐│ Wow, where did all the time go? I hope you have learned enough of the ││ C language to feel comfortable creating your own programs. ││ ││ There are many other subjects to be explored in C which I am saving for ││ an ADVANCED ADVENTURE IN C. Look for it real soon!!! Until then please ││ pass this on to your friends and neighbors and don't forget to ease your ││ conscious by sending your contribution to: ││ ││ ││ Joaquin Valentine ││ 4209 C Moyer Street ││ Wahiawa, Hi 96786 ││ ││ Until we meet again, Happy Programming ││ ││ ││ ││ │└──────────────────────────────────────────────────────────────────────────────┘